/* Copyright (c) 2025 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include <regex>
#include "common.h"
#include "certificate/certificate_parser.h"
#include "certificate/certificate.h"

static string split_common_name_from_subject(const string& subject)
{
    regex pattern(R"(CN=(\w+),)");
    smatch match;

    if (regex_search(subject, match, pattern) && match.size() > 1) {
        return match[1].str();
    }

    return "";
}

int32_t Certificate::InitCertificateInfo(const vector<uint8_t>& der_data)
{ 
    auto [ret, cert_info] = get_cert_info(der_data.data(), der_data.size());
    if (ret != RET_OK) {
        debug_log(DLOG_ERROR, "get certificate info failed");
        return RET_ERR;
    }

    certificateType          = PEM;
    certificateUsageType     = TrustedComponentCert;
    fingerPrint              = cert_info.fingerprint;
    fingerPrintHashAlgorithm = cert_info.fingerprintAlgorithm;
    issuer                   = cert_info.issuer;
    subject                  = cert_info.subject;
    keyUsage                 = cert_info.keyUsage;
    keyUsageString           = cert_info.keyUsageString;
    serialNumber             = cert_info.serialNumber;
    signatureAlgorithm       = cert_info.signatureAlgorithm;
    validNotBefore           = cert_info.validNotBefore;
    validNotAfter            = cert_info.validNotAfter;
    certCount                = 1;
    keyLength                = cert_info.keyLength;
    publicKey                = cert_info.publicKey;
    commonName               = split_common_name_from_subject(cert_info.subject);
    hashVal                  = cert_info.hashVal;

    return RET_OK;
}